package com.realshare.frame.component.quartz.service;

import com.realshare.frame.component.quartz.model.SysDbQuartz;
import org.beetl.sql.core.SQLManager;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * 数据库数据处理任务
 * 使用@DisallowConcurrentExecution设置不并发执行
 * author leisure
 * email 15075107120@139.com
 * create 2018-12-14 下午 4:33
 * modify 2018-12-14 下午 4:33
 **/
@Service
@DisallowConcurrentExecution
public class ListenQuartzScheduler extends QuartzJobBean implements Serializable {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SQLManager sqlManager;
    @Autowired
    private QuartzManager quartzManager;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        listenDbQuartz();
    }

    private void listenDbQuartz() {
        log.info("开始扫描数据库数据处理定时任务动态变更监听");
        List<SysDbQuartz> quartzList = sqlManager.query(SysDbQuartz.class).andGreat("status", "1").select();
        for (SysDbQuartz sysQuartz : quartzList) {
            final String name = sysQuartz.getName();
            int taskStatus = sysQuartz.getTaskStatus();
            final String group = "SysDbQuartz";
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("sysQuartzId", sysQuartz.getId());
            log.info("监听到【" + name + "】数据库数据处理定时任务动态变更，已完成任务加载");
            quartzManager.scheduleJob(name, group, name, sysQuartz.getCron(), DBQuartzScheduler.class, jobDataMap);
            if (taskStatus == 2) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(10000);
                            log.info("监听到【" + name + "】数据库数据处理定时任务动态变更，需立即执行一次,已启动立即执行任务");
                            quartzManager.triggerJob(name, group);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                new Thread(runnable).start();
            }
            sysQuartz.setTaskStatus(1);
            sqlManager.updateById(sysQuartz);
        }
        log.info("结束扫描数据库数据处理定时任务动态变更监听");
    }
}
